package com.smyh.thread;

import android.os.Bundle;
import android.os.Message;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

import org.apache.mina.core.session.IoSession;

import com.smyh.UIM.device.DeviceUpdateFm;
import com.smyh.common.MinaClientThread;
import com.smyh.protcol.device.CMDUtil;
import com.smyh.server.ToastShowMsgThread;

public class UpdateDeviceProgramThread extends Thread {

	String filePath;
	int prev;

	/** 初始化-升级文件路径 */
	public UpdateDeviceProgramThread(String filePath) {
		this.prev = prev;
		this.filePath = filePath;
	}

	@Override
	public void run() {
		IoSession session = MinaClientThread.session;
		if (session == null || session.isClosing()) return;
		FileInputStream input = null;
		try {
			File file = new File(filePath);//filePath
			long fileLength = file.length();
			input = new FileInputStream(file);
			// 设置dataAddr、updateState初始值
			session.setAttribute("dataAddr", 0);
			int updateState = 1; // 1-接收成功、2-接收失败、5-未应答、10-上传成功
			session.setAttribute("updateState", updateState);
			byte[] bs = new byte[240];
			int sendAddr = 0, lastSendSize = 0, repeat = 0;
			while (!session.isClosing()) { // 连接断开时也中断上传过程
				int dataAddr = (Integer) session.getAttribute("dataAddr");
				updateState = (Integer) session.getAttribute("updateState");
				if (updateState == 10) break; // 上传完成
				if (updateState == 1 && dataAddr == sendAddr) { // 升级包接收确认
					session.setAttribute("updateState", 5);
					int len = input.read(bs);
					bs = len <= 0 ? null : (len < bs.length ? Arrays.copyOf(bs, len) : bs);
					sendAddr += lastSendSize;
//					UpdateProgramDeviceUI_Cache.sendBytesField.setText(sendAddr + "/" + fileLength);
					//数据进度状态：
//					showProgressStr = sendAddr + "/" + fileLength;
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("1",sendAddr + "/" + fileLength);
					// 消息数据
					message.what = 1;
					message.setData(bundle);
					DeviceUpdateFm.freshProgress(message);
					if (bs != null) {

						session.write(CMDUtil.getUpdatePack(bs, sendAddr));
						lastSendSize = bs.length;
						repeat = 0; // 重置重发时间
					} else { // 设置上传完成标识
						session.setAttribute("updateState", 10);
					}
				} else { // 升级包接收失败或未应答
					repeat++;
					if (repeat > 60) break; // 超过重发时间（1分钟）
					if (repeat % 3 == 0 && bs != null) {
						session.write(CMDUtil.getUpdatePack(bs, sendAddr)); // 每3秒重发一次
					}
				}
				Thread.sleep(1000); // 延时1秒
			}
			if (updateState == 10) {
				new Thread(new ToastShowMsgThread("升级成功！")).start();
				this.interrupt();
			} else {
				new Thread(new ToastShowMsgThread("升级失败！")).start();
				this.interrupt();
			}
		} catch (InterruptedException e) {
			new Thread(new ToastShowMsgThread("升级中断！")).start();
			this.interrupt();
		} catch (IOException e) {
			new Thread(new ToastShowMsgThread("读取升级文件发生异常，升级失败！")).start();
			this.interrupt();
		} finally {
			if (input != null) {
				try {
					input.close();
					this.interrupt();
				} catch (IOException e) {
				}
			}
		}
	}
}
